package com.pleasure.gm.criminalintent;

import android.content.Context;
import android.util.Log;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.UUID;

/**
 * Created by Administrator on 2016-01-05.
 */
public class CrimeLab {
    private static CrimeLab sCrimeLab;
    private Context mAppContext;

    private static final String TAG = "CrimeLAB";
    private static final String FILENAME = "crime.json";
    private CrimeIntentJSONSerializer mSaver;

    public ArrayList<Crime> getmCrimes() {
        return mCrimes;
    }

    private ArrayList<Crime> mCrimes;

    private CrimeLab(Context mAppContext){
        this.mAppContext = mAppContext;
        //mCrimes = new ArrayList<Crime>();
        mSaver = new CrimeIntentJSONSerializer(mAppContext, FILENAME);
        try{
            mCrimes = mSaver.loadCrimes();
        }catch (Exception e){
            mCrimes = new ArrayList<Crime>();
            Log.e(TAG,"Error load crimes",e);
        }

//        for (int i = 0; i < 100; i++) {
//            Crime c = new Crime();
//            c.setTitle("Crime #" + i);
//            c.setmSolved(i%2 == 0);
//            mCrimes.add(c);
//        }
    }

    public Crime getCrime(UUID id){
        for (Crime c : mCrimes){
            if(c.getId().equals(id)){
                return c;
            }
        }

        return null;
    }

    public void addCrime(Crime c){
        mCrimes.add(c);
    }

    public void deleteCrime(Crime c){
        mCrimes.remove(c);
    }
    public static CrimeLab get(Context context){
        if(sCrimeLab == null){
            sCrimeLab = new CrimeLab(context.getApplicationContext());
        }

        return sCrimeLab;
    }

    public boolean saveCrimes(){
        try{
            mSaver.saveCrimes(mCrimes);
            return true;
        }catch (Exception e){
            Log.e(TAG,"Error saving crime:",e);
            return false;
        }
    }


}
